#include "stdafx.h"
#include "utility.h"

HINSTANCE			g_hInstance = 0;
HANDLE				g_hMutex = 0;

stCommand::stCommand()
{
	Poco::LocalDateTime ldt;
	btTime[0] = ldt.hour();
	btTime[1] = ldt.minute();
	btTime[2] = ldt.second();
}

stCommand::stCommand(byte cmd, WORD id, byte servtype)
	: btCommandType(cmd)
	, btServiceType(servtype)
{
	setId(id);
	Poco::LocalDateTime ldt;
	btTime[0] = ldt.hour();
	btTime[1] = ldt.minute();
	btTime[2] = ldt.second();
	resetVerify();
}

void stCommand::resetVerify(){
	btVerify = 0;
	const byte* buf = reinterpret_cast<const byte*>(this);
	for (int i = 0; i < 15; i++){
		btVerify += buf[i];
	}
}

bool stCommand::verify() const{
	byte bt = 0;
	const byte* buf = reinterpret_cast<const byte*>(this);
	for (int i = 0; i < 15; i++){
		bt += buf[i];
	}
	ASSERT(bt == btVerify);
	return bt == btVerify;
}

wstring stCommand::getStrID() const{
	wstring tmp;
	std_wstring_format(tmp, L"%02X%02X", btDeviceID[0], btDeviceID[1]);
	return std::move(tmp);
}

WORD stCommand::getId() const{
	return _ttoi(getStrID().c_str());
}

void stCommand::setId(int id)
{
	BYTE bf[4] = { 0 };
	char string[10] = { 0 };
	sprintf_s(string, 10, "%04d", id);
	for (int i = 0; i < 4; ++i)
	{
		if ((string[i] >= '0') && (string[i] <= '9'))
			bf[i] = string[i] - '0';
	}
	btDeviceID[0] = (BYTE)(bf[0] << 4) | bf[1];
	btDeviceID[1] = (BYTE)(bf[2] << 4) | bf[3];
}

Timespan stCommand::getTime() const
{
	return Timespan(0, btTime[0], btTime[1], btTime[2], 0);
}


wstring& std_wstring_format(wstring& _str, const wchar_t * _Format, ...) {
	va_list marker = NULL;
	va_start(marker, _Format);
	size_t num_of_chars = _vscwprintf_p(_Format, marker);
	_str.resize(num_of_chars);
	vswprintf_s((wchar_t *)_str.data(), _str.size() + 1, _Format, marker);
	va_end(marker);
#ifdef DEBUG
	const wchar_t* pbuf = _str.c_str();
	assert(L'\0' == pbuf[_str.size()]);
#endif
	return _str;
}





CString GetTransStr(UINT uStrID)
{
	CString str;
	str.LoadString(g_hInstance, uStrID);
	return str;
}